#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基础配置类

定义所有环境配置的基础结构和默认值。

作者: AI Assistant
创建时间: 2024
"""

import os
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class DatabaseConfig:
    """数据库配置"""
    type: str = 'sqlite'
    host: str = 'localhost'
    port: int = 5432
    database: str = 'wechat_robot'
    username: str = 'postgres'
    password: str = ''
    sslmode: str = 'prefer'
    timeout: int = 10
    application_name: str = 'wechat_robot'
    charset: str = 'utf8mb4'
    path: Optional[str] = None  # SQLite数据库文件路径
    
    def get_database_url(self) -> str:
        """获取数据库连接URL"""
        if self.type == 'sqlite':
            db_path = self.path or os.path.join(os.getcwd(), f'{self.database}.db')
            return f'sqlite:///{db_path}'
        elif self.type == 'postgresql':
            return f'postgresql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?sslmode={self.sslmode}&application_name={self.application_name}'
        elif self.type == 'mysql':
            return f'mysql+pymysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset={self.charset}'
        else:
            raise ValueError(f'不支持的数据库类型: {self.type}')


@dataclass
class FlaskConfig:
    """Flask应用配置"""
    host: str = '0.0.0.0'
    port: int = 5000
    debug: bool = True
    secret_key: str = 'dev-secret-key-change-in-production'
    environment: str = 'development'
    testing: bool = False
    

@dataclass
class LoggerConfig:
    """日志配置"""
    level: str = 'DEBUG'  # 修改默认日志级别为DEBUG，以便能够看到调试日志
    file_path: str = 'logs/wechat_robot.log'
    max_size: int = 10  # MB
    backup_count: int = 5
    format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    date_format: str = '%Y-%m-%d %H:%M:%S'
    console_output: bool = True
    file_output: bool = True
    

@dataclass
class WechatConfig:
    """微信配置"""
    wechat_path: Optional[str] = None
    is_maximize: bool = True
    close_wechat: bool = False
    auto_reply_enabled: bool = True
    default_reply_message: str = '收到！'
    welcome_enabled: bool = False
    welcome_template: str = '欢迎 @{member_name} 加入群聊！🎉'
    reply_to_private: bool = True
    reply_to_group_at_only: bool = True
    

@dataclass
class NewsConfig:
    """新闻推送配置"""
    enabled: bool = False
    push_time: str = '09:00'
    target_groups: List[str] = field(default_factory=list)
    api_url: Optional[str] = None
    api_key: Optional[str] = None
    

@dataclass
class SecurityConfig:
    """安全配置"""
    api_access_token: Optional[str] = None
    cors_origins: List[str] = field(default_factory=lambda: ['http://localhost:3000', 'http://127.0.0.1:3000'])
    max_upload_size: int = 50  # MB
    

@dataclass
class PathConfig:
    """路径配置"""
    backup_dir: str = 'backups'
    temp_dir: str = 'temp'
    log_dir: str = 'logs'
    
    def __post_init__(self):
        """确保目录存在"""
        for dir_path in [self.backup_dir, self.temp_dir, self.log_dir]:
            Path(dir_path).mkdir(parents=True, exist_ok=True)


class BaseConfig:
    """基础配置类"""
    
    def __init__(self):
        """初始化基础配置"""
        # 从环境变量加载配置
        self.database = DatabaseConfig()
        self.flask = FlaskConfig()
        self.logger = LoggerConfig()
        self.wechat = WechatConfig()
        self.news = NewsConfig()
        self.security = SecurityConfig()
        self.paths = PathConfig()
        

        

        
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'database': self.database.__dict__,
            'flask': self.flask.__dict__,
            'logger': self.logger.__dict__,
            'wechat': self.wechat.__dict__,
            'news': self.news.__dict__,
            'security': self.security.__dict__,
            'paths': self.paths.__dict__
        }
        
    def get_database_url(self) -> str:
        """获取数据库连接URL"""
        return self.database.get_database_url()
        
    def get_flask_config(self) -> Dict[str, Any]:
        """获取Flask配置字典"""
        return {
            'DEBUG': self.flask.debug,
            'TESTING': self.flask.testing,
            'SECRET_KEY': self.flask.secret_key,
            'SQLALCHEMY_DATABASE_URI': self.get_database_url(),
            'SQLALCHEMY_TRACK_MODIFICATIONS': False,
            'SQLALCHEMY_ENGINE_OPTIONS': {
                'pool_timeout': self.database.timeout,
                'pool_recycle': 3600
            }
        }